package com.android.gufengmall.admin;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.gufengmall.App;
import com.android.gufengmall.R;
import com.android.gufengmall.adapter.UserManagerAdapter;
import com.android.gufengmall.bean.UserBean;
import com.android.gufengmall.gen.DaoSession;
import com.android.gufengmall.gen.UserBeanDao;
import com.android.gufengmall.utils.LogUtils;

import java.util.ArrayList;

/**
 * 用户管理
 */
public class UserManagerFragment extends Fragment implements UserManagerAdapter.onCheckSelectListener {

    private static final String TAG = "UserManagerFragment";

    private RecyclerView mRvUserManager;
    private UserManagerAdapter mUserManagerAdapter;

    private ArrayList<UserBean> mUserBeanList = new ArrayList<>();
    private ArrayList<Integer> mSelectCheckBox = new ArrayList<>();
    private App mMyApp;
    private DaoSession mDaoSession;
    private UserBeanDao mUserDao;

    private Button mBtnAdd;
    private Button mBtnDelete;
    private Button mBtnUpdate;
    private EditText mUser;
    private EditText mPass;
    private EditText mAge;
    private EditText mSex;

    public static UserManagerFragment newInstance() {
        return new UserManagerFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user_manager, container, false);
        initView(view);
        initData();
        initListener();
        return view;
    }

    private void initListener() {
        mBtnAdd.setOnClickListener(v -> {
            AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
            dialog.setTitle("添加用户");
            View view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_add_user_manager, null, false);
            mUser = view.findViewById(R.id.et_username);
            mPass = view.findViewById(R.id.et_password);
            mAge = view.findViewById(R.id.et_age);
            mSex = view.findViewById(R.id.et_sex);
            dialog.setNegativeButton("取消", null);
            dialog.setPositiveButton("确定", (dialog1, which) -> {
                String user = mUser.getText().toString().trim();
                String pass = mPass.getText().toString().trim();
                String age = mAge.getText().toString().trim();
                String sex = mSex.getText().toString().trim();
                if (user.isEmpty() || pass.isEmpty() || age.isEmpty() || sex.isEmpty()) {
                    Toast.makeText(requireContext(), "添加内容不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    boolean isAdd = true;
                    for (int i = 0; i < mUserBeanList.size(); i++) {
                        UserBean user1 = mUserBeanList.get(i);
                        if (user1.getUserName().equals(user)) {
                            isAdd = false;
                        }
                    }
                    if (isAdd) {
                        UserBean userBean = new UserBean();
                        userBean.setUserName(user);
                        userBean.setUserPass(pass);
                        userBean.setSex(sex);
                        userBean.setAge(age);
                        mUserDao.insert(userBean);
                        mUserBeanList.add(userBean);
                        Toast.makeText(requireContext(), "添加成功", Toast.LENGTH_SHORT).show();
                        mUserManagerAdapter.notifyDataSetChanged();
                        dialog1.dismiss();
                    } else {
                        Toast.makeText(requireContext(), "添加失败，账号已存在", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            dialog.setView(view);
            dialog.create().show();
        });
        mBtnDelete.setOnClickListener(v -> {
            boolean isDelete = false;
            for (int i = 0; i < mSelectCheckBox.size(); i++) {
                Integer index = mSelectCheckBox.get(i);
                UserBean userBean = mUserBeanList.get(index);
                mUserDao.delete(userBean);
                mUserBeanList.remove(userBean);
                mSelectCheckBox.remove(index);
                isDelete = true;
            }
            if (isDelete) {
                Toast.makeText(requireContext(), "删除成功", Toast.LENGTH_SHORT).show();
                mUserManagerAdapter.notifyDataSetChanged();
            } else {
                Toast.makeText(requireContext(), "删除失败", Toast.LENGTH_SHORT).show();
            }
        });
        mBtnUpdate.setOnClickListener(v -> {
            if (mSelectCheckBox.size() != 1) {
                Toast.makeText(requireContext(), "请选择一个数据进行修改，不可多选或少选", Toast.LENGTH_SHORT).show();
            } else {
                UserBean userBean = mUserBeanList.get(mSelectCheckBox.get(0));
                AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
                dialog.setTitle("修改用户");
                View view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_add_user_manager, null, false);
                mUser = view.findViewById(R.id.et_username);
                mPass = view.findViewById(R.id.et_password);
                mAge = view.findViewById(R.id.et_age);
                mSex = view.findViewById(R.id.et_sex);
                mUser.setText(userBean.getUserName());
                mPass.setText(userBean.getUserPass());
                mAge.setText(userBean.getAge());
                mSex.setText(userBean.getSex());
                dialog.setNegativeButton("取消", null);
                dialog.setPositiveButton("确定", (dialog1, which) -> {
                    String user = mUser.getText().toString().trim();
                    String pass = mPass.getText().toString().trim();
                    String age = mAge.getText().toString().trim();
                    String sex = mSex.getText().toString().trim();
                    if (user.isEmpty() || pass.isEmpty() || age.isEmpty() || sex.isEmpty()) {
                        Toast.makeText(requireContext(), "修改内容不能为空", Toast.LENGTH_SHORT).show();
                    } else {
                        userBean.setUserName(user);
                        userBean.setUserPass(pass);
                        userBean.setAge(age);
                        userBean.setSex(sex);
                        mUserDao.update(userBean);
                        Toast.makeText(requireContext(), "修改成功", Toast.LENGTH_SHORT).show();
                        mUserManagerAdapter.notifyDataSetChanged();
                        dialog1.dismiss();
                    }
                });
                dialog.setView(view);
                dialog.create().show();
            }
        });
    }

    private void initView(View view) {
        mRvUserManager = view.findViewById(R.id.rv_user_manager);
        mBtnAdd = view.findViewById(R.id.btn_add);
        mBtnDelete = view.findViewById(R.id.btn_delete);
        mBtnUpdate = view.findViewById(R.id.btn_update);
    }

    private void initData() {

        mMyApp = (App) getActivity().getApplication();
        mDaoSession = mMyApp.getDaoSession();
        mUserDao = mDaoSession.getUserBeanDao();
        mUserBeanList.addAll(mUserDao.loadAll());

        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvUserManager.setLayoutManager(layoutManager);

        mUserManagerAdapter = new UserManagerAdapter(requireContext(), mUserBeanList);
        mUserManagerAdapter.setOnCheckSelectListener(this);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL);
        mRvUserManager.addItemDecoration(dividerItemDecoration);
        mRvUserManager.setAdapter(mUserManagerAdapter);
    }

    @Override
    public void OnCheckSelect(int position, boolean isCheck) {
        if (isCheck) {
            mSelectCheckBox.add(position);
        } else {
            for (int i = 0; i < mSelectCheckBox.size(); i++) {
                Integer integer = mSelectCheckBox.get(i);
                if (integer == position) {
                    mSelectCheckBox.remove(i);
                }
            }
        }
    }
}